package com.vagavaga.bizworld;

import java.util.HashMap;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import com.vagavaga.bizworld.jpatx.JPATX;

public class SessionManager {
    private static final HashMap<SessionProducer, SessionManager> INSTANCES = new HashMap<SessionProducer, SessionManager>();

    private SessionProducer producer;

    public static SessionManager create(SessionProducer producer) {
        synchronized (INSTANCES) {
            if (INSTANCES.containsKey(producer)) {
                return INSTANCES.get(producer);
            } else {
                SessionManager manager = new SessionManager(producer);
                INSTANCES.put(producer, manager);
                return manager;
            }
        }
    }

    public static SessionManager create(String persistentUnitName) {
        DefaultSessionProducer producer = new DefaultSessionProducer(persistentUnitName);
        return create(producer);
    }

    private SessionManager(SessionProducer producer) {
        if (producer == null) throw new IllegalArgumentException("SessionProducer must be provided");
        this.producer = producer;
    }

    public EntityManager createEntityManager() {
        return JPATX.entityManager(producer);
    }

    public EntityManager createNewEntityManager() {
        return JPATX.createEntityManager(producer);
    }
    
    public static void close(EntityManager em) {
        JPATX.close(em);
    }
    
    public static void rollback(EntityTransaction tx) {
        JPATX.rollback(tx);
    }
}
